//
//  AudioPlayer.m
//  MusicPlayer
//
//  Created by lanou3g on 15/9/17.
//  Copyright (c) 2015年 Jenney. All rights reserved.
//

#import "AudioPlayer.h"
#import <AVFoundation/AVFoundation.h>


@interface AudioPlayer ()

{
    BOOL _isPrepare;
    BOOL _isPlaying;
}

//播放器对象
@property (nonatomic,strong)AVPlayer * player;
//播放定时器
@property (nonatomic,strong)NSTimer * timer;


@end


@implementation AudioPlayer
singleton_implementation(AudioPlayer)

-(instancetype)init
{
    if (self = [super init]) {
        //注册通知
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(timeEndAction:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    }
    return self;
}


#pragma mark-- 私有方法
//音乐播放完毕
- (void)timeEndAction:(id)sender{
    //如果代理存在,并且可以执行协议方法
    if (self.delegate && [self.delegate respondsToSelector:@selector(audioPlayerDidFinish:)]) {
        [self.delegate audioPlayerDidFinish:self];
    }
}

//播放过程中,一直执行此方法
- (void)playingAction:(NSTimer *)sender
{
    //不断执行代理方法
    if (self.delegate && [self.delegate respondsToSelector:@selector(audioPlayer:playingWithProgress:)]) {
        float progress = 1.0 * self.player.currentTime.value / self.player.currentTime.timescale;
        
        [self.delegate audioPlayer:self playingWithProgress:progress];
        
        //将timer添加到runloop
        [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    }
}



#pragma mark-- 公开方法
// 根据url播放音乐
- (void)setPreparePlayMusicURLStr:(NSString *)urlString
{
    if (!urlString) {
        return;
    }
    NSURL *urlStr=[[NSURL alloc]init];
    if ([[urlString substringToIndex:4]isEqualToString:@"http"]) {
        urlStr=[NSURL URLWithString:urlString];
    }else{
        
        NSURL *str1 = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
        NSString *s = [str1 absoluteString];
        
        s = [NSString stringWithFormat:@"%@%@",s,urlString];
        urlStr = [NSURL URLWithString:s];
    }
    
    // 如果当前正在播放音乐，把播放监听移除
    if (self.player.currentItem) {
        [self.player.currentItem removeObserver:self forKeyPath:@"status"];
    }
    
    // 根据URL创建AVPlayerItem对象
    AVPlayerItem *playerItem = [[AVPlayerItem alloc] initWithURL:urlStr];
    [playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
    
    // 根据给定的item，替换当前播放的音乐
    [self.player replaceCurrentItemWithPlayerItem:playerItem];
}




// 播放
- (void)play
{
    if (!_isPrepare) {
        return;
    }
    
    _isPlaying = YES;
    [self.player play];
    
    
    // 设置定时器
    if (self.timer) {
        return;
    }
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:.1 target:self selector:@selector(playingAction:) userInfo:nil repeats:YES];
    
}



// 暂停
- (void)pause
{
    if (!_isPlaying) {
        return;
    }
    
    [self.player pause];
    _isPlaying = NO;
    [self.timer invalidate];
    self.timer = nil;
}



// 停止
- (void)stop
{
    if (!_isPlaying) {
        return;
    }
    
    // 暂停
    [self.player pause];
    
    // 播放时间，设置到0秒
    [self.player seekToTime:CMTimeMake(0, self.player.currentTime.timescale)];
    _isPlaying = NO;
}



// 设置音量
- (void)setVolume:(float)volume
{
    self.player.volume = volume;
}

// 获取音量
- (float)volume
{
    return self.player.volume;
}

// 获取播放时间
- (void)seekToTime:(float)time
{
    //先暂停
    [self pause];
    
    //设置开始播放的时间
    [self.player seekToTime:CMTimeMakeWithSeconds(time, self.player.currentTime.timescale) completionHandler:^(BOOL finished) {
        if (finished) {
            [self play];
        }
    }];
}

-(BOOL)isPlaying
{
    return _isPlaying;
}

#pragma mark-- 监听方法
- (void)observeValueForKeyPath:(nullable NSString *)keyPath ofObject:(nullable id)object change:(nullable NSDictionary *)change context:(nullable void *)context
{
    if ([keyPath isEqualToString:@"status"]) {
        
        // 获取当前状态
        AVPlayerItemStatus status = [change[@"new"] integerValue];
        
        switch (status) {
            case AVPlayerItemStatusReadyToPlay: { // 准备好了，可以播放，直接播放
                _isPrepare = YES;
                [self play];
                break;
            }
            case AVPlayerItemStatusFailed: {
                NSLog(@"错误");
                break;
            }
            case AVPlayerItemStatusUnknown: {
                NSLog(@"未知");
                break;
            }
                
            default:
                break;
        }
    }
}




#pragma mark-- 懒加载
-(AVPlayer *)player
{
    if (!_player) {
        _player = [[AVPlayer alloc] init];
    }
    return _player;
}

-(NSTimer *)timer
{
    if (!_timer) {
        _timer = [[NSTimer alloc] init];
    }
    return _timer;
}


//移除通知
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self forKeyPath:AVPlayerItemDidPlayToEndTimeNotification];
}

@end
